package com.ynashk.emd.datasource;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.Arrays;

/**
 *
 * @author user
 */
@Aspect
@Order(-1)
@Component
@Slf4j
public class DynamicDataSourceAspect {

    @Pointcut("execution(* com.ynashk.emd.mapper.YwDao.*(..))")
    public void daoSwitchDataSource() {
    }

    @Before("daoSwitchDataSource()")
    public void println(JoinPoint joinPoint) {
        String dataSource = "primary";
        log.info("==> JoinPoint Method Parameters: " + Arrays.toString(joinPoint.getArgs()));
        log.info("==> Current Access Method: " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName() + "()");
        // 通过调用的方法来分配数据源
        if ("com.ynashk.emd.mapper.YwDao".equals(joinPoint.getSignature().getDeclaringTypeName())) {
            dataSource = "secondary";
        }
        DataSourceNameContextHolder.setDataSourceName(dataSource);
        log.info("==> Current Use DataSource: " + dataSource);
    }

    @After("daoSwitchDataSource()")
    public void afterSwitchDataSource() {
        DataSourceNameContextHolder.resetDataSourceName();
    }

}